#include "ohos_init.h"

#include "stdio.h"
#include "stdint.h"

#include "cmsis_os2.h"
#include "wifiiot_errno.h"
#include "wifiiot_gpio.h"
#include "wifiiot_gpio_ex.h"
#include "wifiiot_i2c.h"
#include "wifiiot_i2c_ex.h"

#include "SHT3x.h"
#include "ssd1306.h"

#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static void Example_Task(void)
{
    // uint8_t i = ' ';
    int ret = 0;
    SHT3x dev;
    uint32_t tickPerSec = osKernelGetTickFreq();
    char *buffer = NULL;

    buffer = malloc(20);
    if (NULL == buffer) printf("malloc fail.\r\n");

    // INIT IIC
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_0, WIFI_IOT_IO_FUNC_GPIO_0_I2C1_SDA);   // GPIO_0复用为I2C1_SDA
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_1, WIFI_IOT_IO_FUNC_GPIO_1_I2C1_SCL);   // GPIO_1复用为I2C1_SCL
    I2cInit(WIFI_IOT_I2C_IDX_1, 400000); /* baudrate: 400kbps */
    I2cSetBaudrate(WIFI_IOT_I2C_IDX_1, 400000);

    // INIT SHT30
    dev.host = WIFI_IOT_I2C_IDX_1;
    dev.slave = SHT3X_ADDR_VSS;
    ret = SHT3X_StartPeriodicMeasurment(&dev, REPEATAB_HIGH, FREQUENCY_1HZ);
    printf("SHT3X_StartPeriodicMeasurment %d.\r\n", ret);

    // INIT OLED
    SSD1306InitCfg(&Font_8x16);
    SSD1306Clear();
    SSD1306RefreshGram();

    while (1)
    {
        osDelay(tickPerSec);

        // 读取测量数值
        ret = SHT3X_ReadMeasurementBuffer(&dev);
        // 输出结果
        if (0 == ret)
        {
            // printf("Humi : %.2f\r\n", dev.data.humidity);
            // printf("Temp : %.2f\r\n", dev.data.temperature);

            // 显示温湿度
            memset(buffer, 0, 20);
            sprintf(buffer, "Temp : %.2lf", dev.data.temperature);
            SSD1306DrawString(0, 16, buffer);

            memset(buffer, 0, 20);
            sprintf(buffer, "Humi : %.2lf", dev.data.humidity);
            SSD1306DrawString(0, 32, buffer);

            SSD1306RefreshGram();
        }
        else
        {
            printf("FAIL.\n");
        }

        // oled 显示
        // SSD1306DrawChar(0, 0, i++);
    }

    free(buffer);
}

#define TASK_STACK_SIZE 1024 * 8
#define TASK_PRIO 25
static void ExampleEntry(void)
{
    osThreadAttr_t attr;

    attr.name = "Example_Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)Example_Task, NULL, &attr) == NULL)
    {
        printf("Falied to create Example_Task!\n");
    }
}

APP_FEATURE_INIT(ExampleEntry);